package com.firsteapps.mobile.android.puzzle;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.firsteapps.mobile.android.puzzle.game.DrawView;
import com.firsteapps.mobile.android.puzzle.game.GameScreen;
import com.firsteapps.mobile.android.puzzle.game.Helper;
import com.firsteapps.mobile.android.puzzle.game.Puzzle;
import com.firsteapps.mobile.android.puzzle.game.PuzzleInfo;
import com.firsteapps.mobile.android.puzzle.util.Consts;
import com.firsteapps.mobile.android.puzzle.util.Utilities;

public class SelectPuzzle extends PostLoginBase {
	private ListView puzzlesList;
	private TextView puzzleSizeViewer, movesCountViewer, attemptsCountViewer, timeLimitViewer, autosolveViewer;
	private DrawView puzzlePreview;
	private ImageView playGame, getMorePuzzles, createdPuzzles, importedPuzzles;
	private LinearLayout selectPuzzlesLayout, puzzleViewerLayout;
	private boolean isPreviewOn = false;
	// private int currentItemPosition = -1;
	private boolean[] selectedPositions;
	private String currentWorkingDirectory;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_puzzle_base);

		puzzleSizeViewer = (TextView) findViewById(R.id.puzzle_size_viewer);
		movesCountViewer = (TextView) findViewById(R.id.moves_count_viewer);
		attemptsCountViewer = (TextView) findViewById(R.id.attempts_count_viewer);
		timeLimitViewer = (TextView) findViewById(R.id.time_limit_viewer);
		autosolveViewer = (TextView) findViewById(R.id.autosolve_viewer);

		puzzlesList = (ListView) findViewById(R.id.created_puzzles_list);
		puzzlesList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		puzzlePreview = (DrawView) findViewById(R.id.puzzleView);
		selectPuzzlesLayout = (LinearLayout) findViewById(R.id.select_puzzles_layout);
		puzzleViewerLayout = (LinearLayout) findViewById(R.id.puzzle_viewer_layout);

		ArrayList<String> items = new ArrayList<String>();
		items.addAll(Arrays.asList(Helper.getPuzzleFiles(this, Consts.FILE_TYPE_INFO, Consts.FOLDER_NAME_INITIAL_PUZZLES)));
		items.addAll(Arrays.asList(Helper.getPuzzleFiles(this, Consts.FILE_TYPE_INFO,
				getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED))));
		selectedPositions = new boolean[items.size()];
		Helper.resetSelectedItem(selectedPositions);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item_puzzles, items) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					LayoutInflater inflater = (LayoutInflater) SelectPuzzle.this
							.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					convertView = inflater.inflate(R.layout.list_item_puzzles, null);
				}

				ImageView selectionView = (ImageView) convertView.findViewById(R.id.puzzle_item_state);
				TextView nameView = (TextView) convertView.findViewById(R.id.puzzle_item_name);
				TextView dateView = (TextView) convertView.findViewById(R.id.puzzle_item_date);
				TextView autosolveView = (TextView) convertView.findViewById(R.id.puzzle_item_autosolvable);

				selectionView.setBackgroundResource(selectedPositions[position] ? R.drawable.puzzle_selected
						: R.drawable.puzzle_not_selected);
				final String currentItem = getItem(position);
				String[] puzzleAttrs = currentItem.substring(currentItem.lastIndexOf("/") + 1).split(Consts.FILENAME_SPLITTER);
				nameView.setText(Helper.getUserName(getUserName()) + "_"
						+ puzzleAttrs[0].substring(0, puzzleAttrs[0].indexOf(".")));
				String dateStr;
				if (puzzleAttrs.length > 1) {
					dateStr = puzzleAttrs[1];
					dateStr = dateStr.replaceFirst("_", "/");
					dateStr = dateStr.replaceFirst("_", "/");
					dateStr = dateStr.replaceFirst("_", " ");
					dateStr = dateStr.replaceFirst("_", ":");
					dateStr = dateStr.replaceFirst("_", ":");
				} else
					dateStr = "Not specified";
				dateView.setText(dateStr);
				autosolveView.setText(puzzleAttrs.length > 2 ? puzzleAttrs[2] : "Not specified");

				return convertView;
			}
		};
		puzzlesList.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				if (!selectedPositions[position]) {
					Helper.resetSelectedItem(selectedPositions);
					selectedPositions[position] = true;
					// ImageView selectedPuzzle = (ImageView) view.findViewById(R.id.puzzle_item_state);
					// selectedPuzzle.setBackgroundResource(R.drawable.puzzle_selected);
					String puzzleName = (String) parent.getItemAtPosition(position);
					PuzzleInfo info = Helper.loadCreatedPuzzle(SelectPuzzle.this, puzzleName);

					puzzleSizeViewer.setText(info.getSize() + ":" + info.getSize());
					movesCountViewer.setText(info.getMoveCount() + (info.getMaxMoves() > 0 ? "/" + info.getMaxMoves() : ""));
					attemptsCountViewer.setText(info.getAttempts()
							+ (info.getMaxAttempts() > 0 ? "/" + info.getMaxAttempts() : ""));
					timeLimitViewer.setText(Helper.getElapsedTime(info.getElapsed())
							+ (info.getMaxTime() > 0 ? "/" + Helper.getElapsedTime(info.getMaxTime() * 1000) : ""));
					autosolveViewer.setText(info.isAutosolvable() ? "YES" : "NO");

					((ArrayAdapter<String>) parent.getAdapter()).notifyDataSetChanged();
					// currentItemPosition = position;
				}
			}
		});
		puzzlesList.setAdapter(adapter);

		createdPuzzles = (ImageView) findViewById(R.id.sp_created_puzzles);
		createdPuzzles.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				if (!isPreviewOn) {
					// currentItemPosition = -1;
					puzzlesList.setItemChecked(puzzlesList.getCheckedItemPosition(), false);

					createdPuzzles.setBackgroundResource(R.drawable.sp_created_puzzles_act);
					importedPuzzles.setBackgroundResource(R.drawable.sp_imported_puzzles);

					currentWorkingDirectory = getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED);

					ArrayAdapter<String> adapter = (ArrayAdapter<String>) puzzlesList.getAdapter();
					adapter.clear();
					String[] items = Helper.getPuzzleFiles(SelectPuzzle.this, Consts.FILE_TYPE_INFO, currentWorkingDirectory);
					if (items != null && items.length > 0) {
						ArrayList<String> list = new ArrayList<String>();
						list.addAll(Arrays.asList(items));
						selectedPositions = new boolean[items.length];
						Helper.resetSelectedItem(selectedPositions);

						// adapter.addAll(list);
						for (String listItem : list) {
							adapter.add(listItem);
						}
					}

					adapter.notifyDataSetChanged();
				}
			}
		});
		importedPuzzles = (ImageView) findViewById(R.id.sp_imported_puzzles);
		importedPuzzles.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				if (!isPreviewOn) {
					// currentItemPosition = -1;
					puzzlesList.setItemChecked(puzzlesList.getCheckedItemPosition(), false);

					createdPuzzles.setBackgroundResource(R.drawable.sp_created_puzzles);
					importedPuzzles.setBackgroundResource(R.drawable.sp_imported_puzzles_act);

					currentWorkingDirectory = getWorkingSubDirectory(Consts.FOLDER_NAME_IMPORTED);

					ArrayAdapter<String> adapter = (ArrayAdapter<String>) puzzlesList.getAdapter();
					adapter.clear();
					String[] items = Helper.getPuzzleFiles(SelectPuzzle.this, Consts.FILE_TYPE_INFO, currentWorkingDirectory);
					if (items != null && items.length > 0) {
						ArrayList<String> list = new ArrayList<String>();
						list.addAll(Arrays.asList(items));
						selectedPositions = new boolean[items.length];
						Helper.resetSelectedItem(selectedPositions);

						// adapter.addAll(list);
						for (String listItem : list) {
							adapter.add(listItem);
						}
					}

					adapter.notifyDataSetChanged();
				}
			}
		});

		getMorePuzzles = (ImageView) findViewById(R.id.sp_get_more_puzzles);

		playGame = (ImageView) findViewById(R.id.sp_base_select_or_play);
		playGame.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int position = puzzlesList.getCheckedItemPosition();
				if (position < 0) {
					Helper.doMessageDialog(SelectPuzzle.this, "Select Puzzle", "No item is selected");
				} else {
					final String selectedPuzzle = puzzlesList.getItemAtPosition(position).toString();
					if (selectedPuzzle != null) {
						AlertDialog dialog = new AlertDialog.Builder(SelectPuzzle.this)
								.setTitle("Select Puzzle")
								.setMessage("Are you sure you want to play the puzzle?")
								.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Intent play = new Intent(SelectPuzzle.this, GameScreen.class);
										play.putExtra(Consts.PUZZLE_KEY, selectedPuzzle);
										startActivity(play);
										finish();
										overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
									}
								})
								.setNegativeButton(android.R.string.cancel,
										new android.content.DialogInterface.OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												dialog.dismiss();
											}
										}).create();
						dialog.show();
					}
				}
			}
		});

		ImageView preview = (ImageView) findViewById(R.id.sp_base_preview);
		preview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isPreviewOn) {
					puzzleViewerLayout.setVisibility(View.GONE);
					selectPuzzlesLayout.setVisibility(View.VISIBLE);
					getMorePuzzles.setVisibility(View.GONE);
					playGame.setVisibility(View.VISIBLE);
					isPreviewOn = !isPreviewOn;
				} else {
					int position = puzzlesList.getCheckedItemPosition();
					if (position < 0) {
						Helper.doMessageDialog(SelectPuzzle.this, "Select Puzzle", "No item is selected");
					} else {
						String selectedPuzzle = puzzlesList.getItemAtPosition(position).toString();
						if (selectedPuzzle != null) {
							PuzzleInfo info = Helper.loadCreatedPuzzle(SelectPuzzle.this, selectedPuzzle);
							if (info == null) {
								Helper.doMessageDialog(SelectPuzzle.this, "Select Puzzle", "Unable to load selected puzzle");
							} else {
								getMorePuzzles.setVisibility(View.VISIBLE);
								playGame.setVisibility(View.GONE);
								selectPuzzlesLayout.setVisibility(View.GONE);
								puzzleViewerLayout.setVisibility(View.VISIBLE);

								info.setTilePositions(null);
								puzzlePreview.setPuzzleSize(info.getSize());
								Puzzle puzzle = new Puzzle(Helper.getBitmap(SelectPuzzle.this, info.getFile()), info);
								puzzlePreview.setFocusable(false);
								puzzlePreview.setPuzzle(puzzle);

								isPreviewOn = !isPreviewOn;
							}
						}
					}
				}
			}
		});

		findViewById(R.id.sp_base_create_puzzle).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Utilities.startActivityWithAnimation(SelectPuzzle.this, CreatePuzzle.class);
			}
		});

		findViewById(R.id.sp_base_delete_puzzle).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int position = puzzlesList.getCheckedItemPosition();
				if (position < 0) {
					Helper.doMessageDialog(SelectPuzzle.this, "Delete Puzzle", "No puzzle is selected to delete");
				} else {
					final String selectedPuzzle = puzzlesList.getItemAtPosition(position).toString();
					if (selectedPuzzle != null) {
						Helper.doMessageDialog(SelectPuzzle.this, "Delete Puzzle", "Are you sure you want to delete the puzzle?",
								new DialogInterface.OnClickListener() {
									@SuppressWarnings("unchecked")
									@Override
									public void onClick(DialogInterface dialog, int which) {
										Helper.deletePuzzle(SelectPuzzle.this, selectedPuzzle, getWorkingDirectory());
										ArrayAdapter<String> adapter = ((ArrayAdapter<String>) puzzlesList.getAdapter());
										adapter.remove(selectedPuzzle);
										adapter.notifyDataSetChanged();
									}
								}, true);
					}
				}
			}
		});
	}
}